package yl.hs.bmipfull.service.material.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yl.hs.bmipfull.daos.material.IOutboundCollectingRecordDao;
import yl.hs.bmipfull.daos.material.IRawMaterialInventoryDao;
import yl.hs.bmipfull.daos.material.IWarehouseDao;
import yl.hs.bmipfull.pojo.material.OutboundCollectingRecordEntity;
import yl.hs.bmipfull.pojo.material.RawMaterialInventoryEntity;
import yl.hs.bmipfull.pojo.material.WarehouseEntity;
import yl.hs.bmipfull.service.material.IOutboundCollectingRecordService;
import yl.hs.bmipfull.utils.DataState;
import yl.hs.bmipfull.utils.HsApp;
import yl.hs.bmipfull.utils.Tl;
import yl.hs.bmipfull.utils.datastate.ActionType;
import yl.hs.bmipfull.viewmodels.PageQuery;
import yl.hs.bmipfull.viewmodels.PageResult;
import yl.hs.bmipfull.viewmodels.material.OutboundCollectingRecordModel;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author 陈昊
 * @apiNote 服务层接口实现
 * @since 2023年06月19日 10时12分16秒 <br/>
 */
@Service
public class OutboundCollectingRecordServiceImpl extends PurchaseBaseService implements IOutboundCollectingRecordService {

    @Autowired
    IOutboundCollectingRecordDao dao;

    @Autowired
    private IWarehouseDao warehouseDao;

    @Autowired
    private IRawMaterialInventoryDao rawMaterialInventoryDao;

    @Override
    public List<OutboundCollectingRecordEntity> queryList(PageQuery pageQuery) throws Exception {
        pageQuery.checkSortSides(OutboundCollectingRecordEntity.class);
        return dao.queryPage(pageQuery.getQuery());
    }

    @Override
    public PageResult<OutboundCollectingRecordEntity> queryPage(PageQuery pageQuery, int rowNum, int page) throws Exception {
        pageQuery.checkSortSides(OutboundCollectingRecordEntity.class);
        var totil=queryList(pageQuery);
        pageQuery.getQuery().put("querySkip", (page - 1) * rowNum);
        pageQuery.getQuery().put("pageSize", rowNum);
        PageResult<OutboundCollectingRecordEntity> result = new PageResult(rowNum);
        result.setRecords(dao.queryCountByCondition(pageQuery.getQuery()));
        result.setPage(page);
        result.setData(dao.queryPage(pageQuery.getQuery()));
        result.setObject(totil.stream().map(OutboundCollectingRecordEntity::getQuantity).reduce(BigDecimal::add));
        return result;
    }


    @Override
    public OutboundCollectingRecordEntity findBySn(String sn) {
        return dao.findBySN(sn);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer saveOutboundCollectingRecord(Map<String, Object> model, String sn) throws Exception {
        var user = HsApp.getCurrent();
        Integer result = 0;
        OutboundCollectingRecordEntity entity = null;
        if (Tl.isEmpty(sn)) {
            //执行保存
            entity = new OutboundCollectingRecordEntity();
            Tl.getChangeLog(entity, model);
            entity.setPYFieldValue();
            entity.setSn(queryNewSN(OutboundCollectingRecordEntity.class));
            entity.setCreatedOn(new Date());
            if (user != null) {
                entity.setCreatedBy(user.getUserName());
            }
            result = dao.insertNew(entity);
            if (result > 0) {
                // 更新库存
                dealInventory(entity);
                writeLog(ActionType.CREATE, entity.getSn(), "插入信息", Tl.toJson(entity), OutboundCollectingRecordEntity.class);
            }
        } else {
            //执行修改
            entity = findBySn(sn);
            Tl.getChangeLog(entity, model);
            entity.setPYFieldValue();
            result = dao.update(entity);
            if (result > 0) {
                writeLog(ActionType.UPDATE, sn, "更新信息", Tl.toJson(entity), OutboundCollectingRecordEntity.class);
            }
        }
        return result;
    }

    @Override
    public Integer saveOutboundCollectingRecordPL(OutboundCollectingRecordModel data) throws Exception {
        var user = HsApp.getCurrent();
        Integer result = 0;
        OutboundCollectingRecordEntity entity = null;
        for (OutboundCollectingRecordEntity datum : data.getData()) {
            entity = datum;
            entity.setPYFieldValue();
            entity.setSn(queryNewSN(OutboundCollectingRecordEntity.class));
            entity.setCreatedBy(user.getUserName());
            result = dao.insertNew(entity);
            if (result > 0) {
                // 更新库存
                dealInventory(entity);
                writeLog(ActionType.CREATE, entity.getSn(), "插入信息", Tl.toJson(entity), OutboundCollectingRecordEntity.class);
            }
        }
        return result;
    }


    private void dealInventory(OutboundCollectingRecordEntity record) {

        RawMaterialInventoryEntity inventory = rawMaterialInventoryDao.findByWHSNAndRmSN(record.getWarehouseSn(), record.getMaterialSn());
        if (inventory != null) {
            var ss = inventory.getQuantity();
            inventory.setQuantity(inventory.getQuantity().subtract(record.getQuantity()));
            writeLog(ActionType.UPDATE,inventory.getSn(),"创建领用记录，库存减少"+record.getQuantity().setScale(2, RoundingMode.DOWN)+"库存由"+ss.setScale(2, RoundingMode.DOWN)+"变为"+inventory.getQuantity().setScale(2, RoundingMode.DOWN),"",RawMaterialInventoryEntity.class);
            rawMaterialInventoryDao.update(inventory);
        }
        WarehouseEntity warehouse = warehouseDao.findBySN(record.getWarehouseSn());
        if (warehouse != null) {
            var dd = warehouse.getInventory();
            warehouse.setInventory(warehouse.getInventory().subtract(record.getQuantity()));
            writeLog(ActionType.UPDATE,warehouse.getSn(),"初期库存"+dd.setScale(2, RoundingMode.DOWN)+"创建领用记录库存减少"+record.getQuantity().setScale(2, RoundingMode.DOWN),"",WarehouseEntity.class);
            warehouseDao.update(warehouse);
        }

    }

    private void multiplyDealInventory(OutboundCollectingRecordEntity record) {

        RawMaterialInventoryEntity inventory = rawMaterialInventoryDao.findByWHSNAndRmSN(record.getWarehouseSn(), record.getMaterialSn());
        if (inventory != null) {
            var quantity = inventory.getQuantity();
            inventory.setQuantity(inventory.getQuantity().add(record.getQuantity()));
            rawMaterialInventoryDao.update(inventory);
            writeLog(ActionType.UPDATE,inventory.getSn(),"删除领用记录，库存增加"+record.getQuantity().setScale(2, RoundingMode.DOWN)+"由"+quantity.setScale(2, RoundingMode.DOWN)+"变为"+inventory.getQuantity().setScale(2, RoundingMode.DOWN),null,RawMaterialInventoryEntity.class);
        }
        WarehouseEntity warehouse = warehouseDao.findBySN(record.getWarehouseSn());
        if (warehouse != null) {
            warehouse.setInventory(warehouse.getInventory().add(record.getQuantity()));
            warehouseDao.update(warehouse);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer delete(String[] sn) {
        Integer result = dao.changeStateBySN(sn, DataState.DELETED.code);
        if (result > 0) {
            for (String s : sn) {
                var ss = dao.findBySN(s);
                if (ss != null) {
                    multiplyDealInventory(ss);
                }
            }
            writeLog(ActionType.DELETE, sn, OutboundCollectingRecordEntity.class);
        }
        return result;
    }
}